package com.jorkyin.waterdrop.ui;

import android.content.Intent;
import android.os.Bundle;

import com.jorkyin.waterdrop.ui.main.MainActivity;
import com.jorkyin.waterdrop.R;
import com.jorkyin.waterdrop.base.BaseActivity;
import com.jorkyin.waterdrop.base.BaseListener;
import com.jorkyin.waterdrop.databinding.ActivityStartBinding;

public class StartActivity extends BaseActivity {
    private ActivityStartBinding mBinding = null;
    private boolean isRunSkip = false;
    private int skipTime = 5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = ActivityStartBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());

        mBinding.btnSkip.setOnClickListener(v -> {
            isRunSkip = false;
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        skip(new BaseListener<Integer>() {
            @Override
            public void onNext(Integer integer) {
                if (integer == null) integer = 0;
                mBinding.btnSkip.setText(getString(R.string.skip_s, integer));
            }

            @Override
            public void onComplete() {
                super.onComplete();
                toMainActivity();
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        isRunSkip = false;
    }

    private void skip(BaseListener<Integer> listener) {
        if (isRunSkip) return;
        isRunSkip = true;
        new Thread(() -> {
            while (isRunSkip) {
                if (skipTime < 0) break;
                if (listener != null) listener.postNext(skipTime);
                skipTime--;

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            if (listener != null) listener.postonComplete();
        }).start();
    }

    private void toMainActivity() {
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }
}